<template>
  <div class="user">
    <el-col :span="24">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户列表</el-breadcrumb-item>
      </el-breadcrumb>
    </el-col>
    <el-col :span="24" class="user-content">
      <!-- 输入框 -->
      <el-col :span="6">
        <el-col :span="18">
          <el-input placeholder="请输入用户名" prefix-icon="el-icon-search" v-model="searchInput"></el-input>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="searchUser">搜索</el-button>
        </el-col>
      </el-col>
      <el-col :span="4">
        <el-button type="primary" @click="isShow = true">添加用户</el-button>
      </el-col>
      <el-col :span="24">
        <el-table :data="arr.users" border style="width: 100%">
          <el-table-column prop="id" label="id" width="140">
          </el-table-column>
          <el-table-column prop="username" label="姓名" width="140">
          </el-table-column>
          <el-table-column prop="email" label="邮箱" width="200">
          </el-table-column>
          <el-table-column prop="create_time" label="电话" width="140">
          </el-table-column>
          <el-table-column prop="role_name" label="角色" width="140">
          </el-table-column>
          <el-table-column prop="mg_state" label="状态" width="140">
          </el-table-column>
          <el-table-column label="操作" width="300">
            <template slot-scope="scope">
              <el-button type="primary" @click="editUser(scope.row)">编辑</el-button>
              <el-button type="danger" @click="delUser(scope.row)">删除</el-button>
              <el-button type="info" @click="setRole(scope.row)">设置</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
      <el-col :span="9" style="margin-top: 20px;">
        <div class="block">
          <div class="block">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pagenum"
              :page-sizes="[2, 4, 6, 8]" :page-size="100" layout="total, sizes, prev, pager, next, jumper"
              :total="total">
            </el-pagination>
          </div>
        </div>
      </el-col>
    </el-col>
    <el-form label-width="100px" class="user-form" v-show="isShow" key="user-form">
      <!-- 标题 -->
      <p>添加用户</p>
      <el-form-item label="用户名" prop="username">
        <el-input type="text" autocomplete="off" v-model="form.username"></el-input>
        <span>{{ form.usernameMsg }}</span>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" autocomplete="off" v-model="form.password"></el-input>
        <span>{{ form.passwordMsg }}</span>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input type="email" autocomplete="off" v-model="form.email"></el-input>
        <span>{{ form.emailMsg }}</span>
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input type="number" v-model="form.phone"></el-input>
        <span>{{ form.phoneMsg }}</span>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="addUser">确认</el-button>
        <el-button @click="isShow = false">取消</el-button>
      </el-form-item>
    </el-form>
    <el-form label-width="100px" class="edit-form" key="edit-form" v-show="editIsShow">
      <!-- 标题 -->
      <p>编辑用户</p>
      <el-form-item label="用户名" prop="username">
        <el-input type="text" autocomplete="off" v-model="editForm.username" :disabled="true"></el-input>
        <span></span>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input type="email" autocomplete="off" v-model="editForm.email"></el-input>
        <span>{{ editForm.emailMsg }}</span>
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input type="number" v-model="editForm.phone"></el-input>
        <span>{{ editForm.phoneMsg }}</span>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="editSubmission">确认</el-button>
        <el-button @click="editIsShow = false">取消</el-button>
      </el-form-item>
    </el-form>
    <!-- 权限设置弹出框 -->
    <el-dialog title="分配角色" :visible.sync="centerDialogVisible" width="30%" center style="line-height: 20px;">
      <el-form :model="form" ref="formRef" label-width="100px" class="demo-ruleForm">
        <el-form-item label="当前用户" prop="username">
          <el-input type="text" autocomplete="off" v-model="form.username" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="当前角色" prop="role_name">
          <el-input type="text" autocomplete="off" v-model="form.role_name" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="role_name">
          <el-select v-model="role_name" placeholder="请选择角色">
            <el-option label="主管" value="30"></el-option>
            <el-option label="测试角色" value="31"></el-option>
            <el-option label="测试角色2" value="34"></el-option>
            <el-option label="超级管理员" value="-1"></el-option>
            <el-option label="test" value="40"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="setRoleSubmission">确认</el-button>

          <el-button @click="centerDialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 遮罩层 -->
    <div class="mask " v-show="isShow || editIsShow"></div>
  </div>
</template>

<script>
import axios from 'axios';
import http from '@/mixins/http.js'
export default {
  mixins: [http()],
  data { returnr /a/e{v1',
  cpge[]ze: 2, h      role_name: '',
      centerDialogVisible: false,
        total: 0,
      form: {
        id:   '',
        usern  ame: '',
          password: '',
          email: '',
          phone: '',
        us  ernameMsg: ''  ,
        passwor  dMsg: '',
        e  mailMsg: '',
        phoneMsg: '  '
      },
        editForm: {  
        usern  ame: '',
        ema  il: '',
        phon  e: '',
        us  ernameMsg: '',
          emailMsg: '',
          phoneMsg: ''
        }

    }
  },
    created() {
    t  his.fetc  hUserData({
        pagesize: this.pagesi  ze,
      pagenum  : this.pagenum
      }).then(data => {
        this.arr = data
        this.total =   dat
a.  t
  }otal   })
  },
    methods: {
    async fetc  hUserData(params = {}) {
        try {
        const  re s = await this.$htt pGet ('/users', params  )
        return res.data.data  
          } catch (error) {
        console.error('请求失败:', er ror) 
          this.$message.error('数据加载失败')
        return null
     }
      },
    handleSizC hang e(val) {
      con sole.l ocovsole.}条`);'请求失败:', 
    )
        this.$message.error(ts.pagesie  = val 
      thisf  etchUserD  ata(  {
        pagesize: this.pages  ize,
        pagenum: this.p agen um
      }).then(dat a =>  {
        this.arr =  data 
      })

    },
    h  andleCurrentChange(val) {
        console.log(`当前页: $ {val}` );
      this.pa  genum = val  
        this.fetchUserData({
        p  agesize: this.pagesize,
          pagenum: this.pagenu m
       }).then(data => { 
         this.arr = data
        })

    },
    async addUser(  ) {
      if (this  .form.username.length < 3 |  | this .f orm.username.length > 6) {  
        this.form.usernameMsg = '用户名长度为3-6位'
        return
      } else {
          this.form.usernameMsg = ''
       }
       if  (thi s.form.pas sword. length < 6 || this.form.pass  word.length   > 15) {
        this.form.passwordMsg = '密码长度为6-15位'
        return
        } else {
        this.form.passwordMs  g = ''
      }
        if (t  his.form.email.length < 6 || this.form  .em ail. length > 15) {

        this.form.emailMsg = '邮箱长度为6-15位'
          return
      } else {
        this.form.emai  lMsg = ' '
       }
       if  (this.form.phone.length  !==  11)   {
        this.form.phoneMsg = '手机号长度为11位'
          return
      } else {
          this.form.phon  eMsg = '' 
       }
      try {
         cons t r es =  await   this.$httpPost('/users', this.form)
        let { data: { data, me  ta } } = res
        if (meta.statu s ===  201) {
          this.fetch  UserData({
            pagesize: this.p  agesize,
            page  num: this.pagenum
          }).then(data   => {
             this.arr =  data
              this.total = data.total
          })
             this .$message({
             me ssage: '添加成功',
              type: 'success'
            })
            this.isShow = fal se
           }
      } catch (error) {  
        console.error('请求失败:'  , error)
        this.$message.error('数据加载  失败')
         ret urn n ul l
        }

    },
      editUser(obj) {
      this.e  ditIsShow = true
        console.log(obj);
      this.editForm.use  rname = obj.username
        this.form.id = obj.id
    },
      async editSubmission() {
        console.log(this.form.id);
      if (this.editForm.email.length < 6 || th is.edi tForm.email.length > 15) {
        thi s.edit Form.ema ilMs g = '邮箱长度为  6-15位'
        return
      } else {  
          this.editForm.emailMsg = ''
      }
        if (this.editForm.phone.length !== 11) {
          this  .editForm.phoneMsg =   '手机号长度为11位'
        return 
         } else {
          this.editForm.phoneMsg = ''
      }
      try {
        const res = aw ait th is.$httpPut('/users/' + this.form.id , this .editForm)
        let { da ta: { da ta, meta } } = res
          if (meta.status === 200) {
          th  is.fetchUserData({
              pagesize: this.pagesize,
              pagenum : this.p agen um
           }).then(dat a => {
             this.arr   = data
          })
          th  is.$ message( {
            message: '  编辑成功',
              type: 'succe  ss'
          })
          this.editIsSho  w = false
        }
      } c atch ( error) {
          co ns ole.error('请求失败:', error)
      
    this.his.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        this.id = obj.id
        try {sa          const res = await this.$httpDelete('/users/' + this.id) }          let { data: { data, meta } } = res t          if (meta.status === 200) {ir            this.fetchUserData({,               pagesize: this.pagesize,                pagenum: this.pagenumex            }).then(data => {'w              this.arr = databj              this.total = data.totalth            })s.            this.$message({ m              type: 'success',ta              message: meta.msg              });            }          } catch (error) { p          console.error('请求失败:', error)            this.$message.error('数据加载失败')          }        }).catch(() => {s.        this.$message({ =          type: 'info',})          message: '已取消删除'          });s'      });
      // try {
      //   const res = await this.$httpDelete('/users/' + obj.id)
      //   let { data: { data, meta } } = res
      //   if (meta.status === 200) {
      //     this.fetchUserData({
      //       pagesize: this.pagesize,
      //       pagenum: this.pagenum
      //     }).then(data => {
      //       this.arr = data
      //       this.total = data.total
      //     })
      //     this.$message({
      //       type: 'success',
      //       message: meta.msg
      //     });
      //   }
      // } catch (error) {
      //   console.error('请求失败:', error)
      //   this.$message.error('数据加载失败')
      //   return null
      // }              message: '已  取消删除'
          });
          } else {
          console.er ror( '请求失败:', error)
          this.$me ssag e.error('数据加载失败')
        }
      } 
     },
    setRole(obj)   {
      console.log(obj);
      this.cent  erDialo  gVisible = true
      this.form.us  ername = obj.userna me
       this.form.role_name   = obj.role_nam  e
      this.role_id = obj.id
    },
    async setRoleSubmission() {
      t ry {
         const tempArray = {
           id:  this.role_id,
          ri d: this. role_name
          }
        const res = await this  .$httpPut('/use rs/' + thi s.role_id + '/ro  le', tempArray)
        let { data:   { data, meta   } } = res
        i  f (meta.status === 200 ) {
           const roleMap = {
              '30': '主管',
            '31':   '测试角色',
             '34': '测 试角色2',
             '-1':  '超级 管理员',
             '40':   'test'
          };
          this.f  etchUserData({
              pagesize:   this.pagesize,
            pagen um: th is. page num
          }).t hen(da ta => {
            this.arr =   data
          })
          this.$messag  e({
              mes  sage: '改成功           type: 'su  caxios.get(chis.baseURL + '/usees',s'  
      )head
r : {
          'Author za ion': this.iokin=       fa},
lse
          }
     } ca tch (error) {
    Inputso le.error('pagenum:请:', erroe um,m e .r('数据加 pagesize:载失败')pag  izu   } 
 
r}h ser() }) t intses =>b{
 '/us  er)s ',  {  
        headers: {
          'Authorization': this.token
        },
        params: {
          query: this.searchInput,
          pagenum: this.pagenum,
          pagesize: this.pagesize
        }
      }).then(res => {

      })
    }
  }
}
</script>

<style scoped lang="scss">
.user-content {
  margin: 20px;
  background-color: #fff;
  height: 800px;
  padding-left: 50px;

}

::v-deep .el-table__header thead tr th {
  height: 30px !important;
  line-height: 30px;
}

.user-form {
  width: 600px;
  height: 500px;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  // align-items: center;
  background-color: #fff;
  position: fixed;
  text-align: left;
  padding-right: 30px;
  left: 30%;
  top: 20%;
  border-radius: 10px;
  z-index: 4;

  p {
    line-height: 20px;
    margin-left: 30px;
  }

  span {
    display: block;
    height: 20px;
  }
}

.mask {
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  position: fixed;
  left: 0;
  top: 0;
  z-index: 3;
}

.edit-form {
  width: 600px;
  height: 400px;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  // align-items: center;
  background-color: #fff;
  position: fixed;
  text-align: left;
  padding-right: 30px;
  left: 30%;
  top: 20%;
  border-radius: 10px;
  z-index: 4;

  p {
    line-height: 20px;
    margin-left: 30px;
  }

  span {
    display: block;
    height: 20px;
  }
}
</style>